package top.javajianghu;

import org.tio.client.ClientChannelContext;
import org.tio.client.ClientTioConfig;
import org.tio.client.TioClient;
import org.tio.core.Node;
import org.tio.core.Tio;
import top.javajianghu.packet.TedisPacket;
import top.javajianghu.utils.TedisMsgUtils;

import java.util.Scanner;

/**
 * @author sintang
 * @date 2020-09-15 14
 */
public class TedisClient {
    public static void main(String[] args) throws Exception {
        Node node = new Node("127.0.0.1",6379);
        TedisClientAioHandler clientAioHandler = new TedisClientAioHandler();
        TedisClientAioListener tedisClientAioListeneri = new TedisClientAioListener();
        ClientTioConfig clientTioConfig = new ClientTioConfig(clientAioHandler,tedisClientAioListeneri,null);
        TioClient tioClient = new TioClient(clientTioConfig);
        ClientChannelContext clientChannelContext = tioClient.connect(node);

        Scanner scanner = new Scanner(System.in);
        while(scanner.hasNextLine()){
            String nextLine = scanner.nextLine();
            if(null != nextLine && !"".equals(nextLine)){
                if("exit".equals(nextLine)){
                    System.exit(1);
                }
                String[] split = nextLine.split(" ");
                String cmd = split[0];
                TedisPacket tedisPacket = new TedisPacket();
                if(split.length == 3){
                    tedisPacket.setBody(TedisMsgUtils.buildCommandBody(cmd,split[1],split[2]));
                }else if(split.length == 2){
                    tedisPacket.setBody(TedisMsgUtils.buildCommandBody(cmd,split[1]));
                }
                Tio.send(clientChannelContext, tedisPacket);
            }
        }
        scanner.close();
    }
}
